package com.dubbo.bootstrap;


import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.webapp.WebAppContext;


public class JettyServer {
    private String contentPath;
    private int port;
    private String webapp;
    private Server server;

    public JettyServer(int port, String webapp, String contentPath) {
        this.port = port;
        this.webapp = webapp;
        this.contentPath = contentPath;
    }

    public void start() throws Exception {
        server = new Server(port);
        server.setStopAtShutdown(true);

        ServerConnector connector = new ServerConnector(server);
        // 设置服务端口
        connector.setPort(port);
        connector.setReuseAddress(false);
        server.setConnectors(new Connector[]{connector});

        // 设置web资源根路径以及访问web的根路径
        WebAppContext webAppCtx = new WebAppContext(webapp, contentPath);
        webAppCtx.setDescriptor(webapp + "/WEB-INF/web.xml");
        webAppCtx.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webAppCtx);

        server.start();

    }

    public void stop() throws Exception {
        if (server != null) {
            server.stop();
        }
    }

}
